package com.vitabuybuy.tv.ui.mine.talent

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.Html
import android.text.InputFilter
import android.text.Spanned
import android.view.View
import android.widget.ScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.luck.picture.lib.PictureSelector
import com.library.common.BuildConfig
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityExpertInfoBinding
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.vitabuybuy.tv.dto.CaseBean
import com.vitabuybuy.tv.dto.FieldLabelDto
import com.vitabuybuy.tv.dto.RegionDto
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.logE
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.NetUrl
import com.library.common.toast.XToast
import com.library.common.util.JsonUtil
import com.library.common.util.PictureUtils
import com.vitabuybuy.tv.ui.UniversalityResultActivity
import com.vitabuybuy.tv.ui.WebViewActivity
import com.vitabuybuy.tv.ui.mine.talent.adapter.CaseAdapter
import com.vitabuybuy.tv.ui.mine.talent.viewmodel.TalentApplyViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_expert_info.*
import kotlinx.android.synthetic.main.activity_expert_info.etFacebookFans
import kotlinx.android.synthetic.main.activity_expert_info.etFacebookId
import kotlinx.android.synthetic.main.activity_expert_info.etFacebookPage
import kotlinx.android.synthetic.main.activity_expert_info.etFacebookPromotionPrice
import kotlinx.android.synthetic.main.activity_expert_info.etIdCard
import kotlinx.android.synthetic.main.activity_expert_info.etInstagramFans
import kotlinx.android.synthetic.main.activity_expert_info.etInstagramId
import kotlinx.android.synthetic.main.activity_expert_info.etInstagramPage
import kotlinx.android.synthetic.main.activity_expert_info.etInstagramPromotionPrice
import kotlinx.android.synthetic.main.activity_expert_info.etTwitterFans
import kotlinx.android.synthetic.main.activity_expert_info.etTwitterId
import kotlinx.android.synthetic.main.activity_expert_info.etTwitterPage
import kotlinx.android.synthetic.main.activity_expert_info.etTwitterPromotionPrice
import kotlinx.android.synthetic.main.activity_expert_info.rlFieldLabel
import kotlinx.android.synthetic.main.activity_expert_info.tvFieldLable
import kotlinx.android.synthetic.main.activity_talent_edit_info.*
import java.util.regex.Matcher
import java.util.regex.Pattern

class ExpertInfoActivity : BaseActivity<TalentApplyViewModel, ActivityExpertInfoBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_expert_info

    private var isAgree = false
    private val genderDialog by lazy { OptionsDialog(mContext) }
    private val picDialog by lazy { OptionsDialog(mContext) }
    private val caseAdapter by lazy { CaseAdapter() }
    private var areaDialog: BottomDialog? = null
    private var REQUEST_CODE_CAMMER = -1
    private var regionId = -1
    private val fieldLabellist = ArrayList<FieldLabelDto>()

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.apply_expert))
        lvCase.apply {
            adapter = caseAdapter
            layoutManager = LinearLayoutManager(mContext)
        }
        tvAgree.text =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                Html.fromHtml(
                    getString(R.string.read_and_agree),
                    Html.FROM_HTML_MODE_COMPACT
                )
            } else {
                Html.fromHtml(getString(R.string.read_and_agree))
            }
        etName.filters = arrayOf(inputFilter, InputFilter.LengthFilter(12))
    }

    val inputFilter = object : InputFilter {
        var pattern =
            Pattern.compile("[^a-zA-Z0-9\u4E00-\u9FA5_]")

        override fun filter(
            charSequence: CharSequence,
            i: Int,
            i1: Int,
            spanned: Spanned,
            i2: Int,
            i3: Int
        ): CharSequence? {
            val matcher = pattern.matcher(charSequence)
            return if (!matcher.find()) {
                null
            } else {
                ""
            }
        }
    }

    override fun observeData() {
        viewModel.getTalentUserInfo()
        viewModel.applyTalentUserInfo.observe(this, Observer {
            if (it.apply) {
                tvIntroduction.visibility = View.GONE
                when (it.status) {
                    "审核中" -> {
                        iv_add_case.visibility = View.GONE
                        llagree.visibility = View.GONE
                        btnSubmit.visibility = View.GONE
                        lv_parent.setEnable(false)
                        tvIntroduction.visibility = View.VISIBLE
                        tvIntroduction.text = getString(R.string.wait_auth)
                    }
                    "拒绝" -> {
                        lv_parent.setEnable(true)
                        tvIntroduction.visibility = View.VISIBLE
                        tvIntroduction.text =
                            getString(R.string.refuse).plus(" : ").plus(it.reason)
                    }
                }
                it.regionList?.run {
                    if (this.isNotEmpty()) {
                        regionId = this[0].id
                        mBinding.tvCountry.text = this[0].name
                    }
                }
                etName.setText(it.realname)
                tvSex.text = it.gender
                etIdCard.setText(it.IDCardNumber)
                etPhone.setText(it.phone)
                it.labelList?.run {
                    fieldLabellist.addAll(this)
                    var labels = ""
                    for (label in fieldLabellist) {
                        labels = "$labels${label.name}、"
                    }
                    mBinding.tvFieldLable.text = if (labels.isNotEmpty()) {
                        labels.substring(0, labels.length - 1)
                    } else labels
                }
                if (!it.facebookLink.isNullOrEmpty()) {
                    etFacebookPage.setText(it.facebookLink)
                }
                etFacebookId.setText(it.facebookId)
                etFacebookPromotionPrice.setText(if (it.facebookPrice == 0.0) "" else it.facebookPrice.toString())
                etFacebookFans.setText(if (it.facebookFansQuantity == 0) "" else it.facebookFansQuantity.toString())
                if (!it.instagramLink.isNullOrEmpty()) {
                    etInstagramPage.setText(it.instagramLink)
                }
                etInstagramId.setText(it.instagramId)
                etInstagramPromotionPrice.setText(if (it.instagramPrice == 0.0) "" else it.instagramPrice.toString())
                etInstagramFans.setText(if (it.instagramFansQuantity == 0) "" else it.instagramFansQuantity.toString())
                if (!it.twitterLink.isNullOrEmpty()) {
                    etTwitterPage.setText(it.twitterLink)
                }
                etTwitterId.setText(it.twitterId)
                etTwitterPromotionPrice.setText(if (it.twitterPrice == 0.0) "" else it.twitterPrice.toString())
                etTwitterFans.setText(if (it.twitterFansQuantity == 0) "" else it.twitterFansQuantity.toString())
                it.experienceList?.run {
                    caseAdapter.setNewData(this)
                }
            }
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            ivChoose, btnSubmit, rlSex, iv_add_case,
            rlCountry, rlFieldLabel, tvAgree
        ){v->
            when (v) {
                tvAgree -> {
                    WebViewActivity.openActivity(mContext, "", "", 16)
                }
                iv_add_case -> {
                    if (caseAdapter.mData.size == 5) {
                        XToast.normal(getString(R.string.most_five_case))
                        return@setOnclickNoRepeat
                    }
                    if (caseAdapter.mData.size > 0) {
                        if (caseAdapter.mData[caseAdapter.mData.size - 1]?.content.isNullOrEmpty() ||
                            caseAdapter.mData[caseAdapter.mData.size - 1]?.image.isNullOrEmpty()
                        ) {
                            XToast.normal(getString(R.string.please_perfect_last_case))
                            return@setOnclickNoRepeat
                        }
                    }
                    caseAdapter.addData(CaseBean())
                }
                rlSex -> {
                    genderDialog.setBtnStr(getString(R.string.male), getString(R.string.female))
                    genderDialog.show()
                }
                rlCountry -> {
                    areaDialog = BottomDialog(this, 1)
                    viewModel.getRegionList(null)
                }
                rlFieldLabel -> {
                    FieldLabelActivity.openActivity(mContext, fieldLabellist)
                }
                ivChoose -> {
                    if (isAgree) {
                        ivChoose.setImageResource(R.drawable.icon_common_choose_n)
                    } else {
                        ivChoose.setImageResource(R.drawable.icon_common_choose_s)
                    }
                    isAgree = !isAgree
                }
                btnSubmit -> {
                    if (etName.text.isEmpty()) {
                        XToast.normal(getString(R.string.name_tip_2))
                        return@setOnclickNoRepeat
                    }
                    if (regionId == -1) {
                        XToast.normal(getString(R.string.please_choose_coutry))
                        return@setOnclickNoRepeat
                    }
                    if (etIdCard.text.isEmpty()) {
                        XToast.normal(getString(R.string.id_card_number_tip))
                        return@setOnclickNoRepeat
                    }
                    if (etPhone.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_phone_number))
                        return@setOnclickNoRepeat
                    }
                    if (fieldLabellist.isEmpty()) {
                        XToast.normal(getString(R.string.please_choose_field_label))
                        return@setOnclickNoRepeat
                    }
                    if (!isAgree) {
                        XToast.normal(getString(R.string.please_agree_agreement))
                        return@setOnclickNoRepeat
                    }
                    val params = HashMap<String, Any>()
                    params["realname"] = etName.text.toString()
                    params["gender"] = tvSex.text.toString()
                    params["IDCardNumber"] = etIdCard.text.toString()
                    params["phone"] = etPhone.text.toString()
                    params["region"] = mapOf(Pair("id", regionId))
                    params["labelList"] = fieldLabellist
                    if (etFacebookPage.text.isNotEmpty()) {
                        params["facebookLink"] = etFacebookPage.text.toString()
                    }
                    if (etFacebookFans.text.isNotEmpty()) {
                        params["facebookFansQuantity"] = etFacebookFans.text.toString()
                    }
                    if (etFacebookId.text.isNotEmpty()) {
                        params["facebookId"] = etFacebookId.text.toString()
                    }
                    if (etFacebookPromotionPrice.text.isNotEmpty()) {
                        params["facebookPrice"] = etFacebookPromotionPrice.text.toString()
                    }
                    if (etInstagramPage.text.isNotEmpty()) {
                        params["instagramLink"] = etInstagramPage.text.toString()
                    }
                    if (etInstagramFans.text.isNotEmpty()) {
                        params["instagramFansQuantity"] = etInstagramFans.text.toString()
                    }
                    if (etInstagramId.text.isNotEmpty()) {
                        params["instagramId"] = etInstagramId.text.toString()
                    }
                    if (etInstagramPromotionPrice.text.isNotEmpty()) {
                        params["instagramPrice"] = etInstagramPromotionPrice.text.toString()
                    }
                    if (etTwitterPage.text.isNotEmpty()) {
                        params["twitterLink"] = etTwitterPage.text.toString()
                    }
                    if (etTwitterFans.text.isNotEmpty()) {
                        params["twitterFansQuantity"] = etTwitterFans.text.toString()
                    }
                    if (etTwitterId.text.isNotEmpty()) {
                        params["twitterId"] = etTwitterId.text.toString()
                    }
                    if (etTwitterPromotionPrice.text.isNotEmpty()) {
                        params["twitterPrice"] = etTwitterPromotionPrice.text.toString()
                    }
                    val executorMap = HashMap<String, Any>()
                    executorMap["executor"] = params
                    if (caseAdapter.mData.isNotEmpty()) {
                        executorMap["experienceList"] = caseAdapter.mData
                    }
                    JsonUtil.toJson(executorMap).logE()
                    viewModel.applyTalent(executorMap)
                }
            }
        }
        genderDialog.onTwoClick = {
            tvSex.text = getString(R.string.female)
        }
        genderDialog.onOneClick = {
            tvSex.text = getString(R.string.male)
        }
        caseAdapter.onItemImageListenter = { position ->
            AndPermission.with(this)
                .runtime()
                .permission(Permission.Group.CAMERA, Permission.Group.STORAGE)
                .onDenied {
                    if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                        // 这些权限被用户总是拒绝。
                        XToast.normal(getString(R.string.request_necessary_permissions))
                    }
                }
                .onGranted {
                    REQUEST_CODE_CAMMER = position
                    picDialog.show()
                }.start()
        }
        picDialog.onTwoClick = {
            PictureUtils.openAluamOneRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        picDialog.onOneClick = {
            PictureUtils.openCameraRectangle(mContext, REQUEST_CODE_CAMMER)
        }
//        caseAdapter.setOnFocusChangeListener = {
//            Handler().postDelayed({
//                scrollView.fullScroll(ScrollView.FOCUS_DOWN)
//            }, 200)
//        }
//        onFocusClick({ _, hasFocus ->
//            if (hasFocus) {
//                Handler().postDelayed({
//                    scrollView.fullScroll(ScrollView.FOCUS_DOWN)
//                }, 200)
//            }
//        }, etTwitterId,etTwitterPage,etTwitterPromotionPrice,etTwitterFans)
    }

    fun onFocusClick(l: (view: View, hasFocus: Boolean) -> Unit, vararg vs: View) {
        for (v in vs)
            v.setOnFocusChangeListener { v, hasFocus ->
                l(v, hasFocus)
            }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            regionId = selectAble?.id ?: -1
                            mBinding.tvCountry.text = selectAble?.name
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            2 -> {
                caseAdapter.mData[msg.arg1]?.image =
                    NetUrl.FILE_PROFILE.plus(msg.obj as String)
                caseAdapter.notifyItemChanged(msg.arg1)
            }
            3 -> {
                UniversalityResultActivity.openActivity(
                    mContext,
                    UniversalityResultActivity.FROM_APPLY_TALENT_SUCCESS
                )
                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_CAMMER -> {
                val path = PictureSelector.obtainMultipleResult(data)[0].cutPath
                viewModel.uploadImage(path, REQUEST_CODE_CAMMER)
            }
            10001 -> {
                fieldLabellist.clear()
                fieldLabellist.addAll(data?.getSerializableExtra("labelList") as ArrayList<FieldLabelDto>)
                var labels = ""
                for (label in fieldLabellist) {
                    labels = "$labels${label.name}、"
                }
                tvFieldLable.text = if (labels.isNotEmpty()) {
                    labels.substring(0, labels.length - 1)
                } else labels
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, ExpertInfoActivity::class.java)
        }
    }
}
